package net.feling.hq711;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.feling.datastructure.myArrayList;
import net.feling.hq711.web.XMLHandler;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.WindowManager;

/**
 * 
 * @author chenyan@feling.net
 * 
 */
public class Config extends Application {
	
	public static  ArrayList<Bundle> goods_in_trolley = new ArrayList<Bundle>(); 
	
//	private String server = "http://feling.net/hq711/";
	private String server = "http://182.92.214.222/hq711/";
	
	/**
	 * 
	 * @return server = "http://182.92.214.222/hq711/"
	 */
	public String getServer() {
		return server;
	}



	@Override
	public void onCreate() {
		super.onCreate();
		
		// TODO 读取网络上或文件里保存的购物车商品
		if  (Config.goods_in_trolley.isEmpty()){
		SharedPreferences preferences = getSharedPreferences("trolley", 0);
		System.out.println("ss"+ preferences.getString("trolley",""));
		List<HashMap<String, String>> trolley = XMLHandler.execute(preferences.getString("trolley",""), "goods");
		if ( trolley != null){
			Config.goods_in_trolley = toBundleList(trolley);
		}
		}
	}

	
	/**
	 * map列表 转成bundle列表
	 * @param list 
	 * @return
	 */
	private ArrayList<Bundle> toBundleList(List<HashMap<String, String>> list){
		ArrayList<Bundle> bundlelist = new ArrayList<Bundle>(); 
		for (int i = 0; i < list.size(); i++) {
			Bundle bundle = new Bundle();
			Iterator<String> it = list.get(i).keySet().iterator();
			while (it.hasNext()) {
				String key = it.next();
				if ("number".equals(key)){
					bundle.putInt(key, Integer.parseInt(list.get(i).get(key)));
				}else{
				bundle.putString(key, list.get(i).get(key));
				}
			}
			bundlelist.add(bundle);
		}
		return bundlelist;
	}
	/**
	 * ArrayList<Bundle> 转xml
	 */
	public static String toXML(ArrayList<Bundle> list) {
		String s1 = "<goodslist>";
		String s2 = "";
		String s3 = "</goodslist>";
		for(int i=0;i<list.size(); i++){
			String s21 = "<goods>";
			String s22 = "";
			String s23 = "</goods>";
			Set<String> keyset = ( list.get(i)).keySet();
			Iterator<String> it = keyset.iterator();
			while(it.hasNext()){
				String key = it.next();
				if ("number".equals(key)){
					s22 = s22 + "<"+key+">" +String.valueOf((list.get(i)).getInt(key)) + "</"+key+">";
				}else{
				s22 = s22 + "<"+key+">" +(list.get(i)).getString(key) + "</"+key+">";
				}
			}
		s2 = s2 + s21 + s22 + s23;
		}
		return s1 + s2 + s3;
	};
	
}
